package com.ucar.training.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;

/**
 * @author XiongMM
 * @date 2019/7/26 15:42
 * @description
 *
 * requestInitialized()方法就是在一个HttpRequest创建完成时的监听，在该方法中可以对刚组建好的HttpRequest进行操作。

在上面的例子中，代码维护了一个WebService的request请求数并放到了上下文中。另外，方法中还输出了这个请求的ServerName，端口，URL，URI等信息。

如果用户提交了一个这样的请求：

http://localhost:9080/dangwebx-tst/tms/bms/billingQaReportController/datagrid.do?field=id,code,applyDate,filename,reportType,applyUser,outPath

那么监听器可能会有这样的输出：

MyServletRequestListener Init

当前请求数：19

serverName:localhost

serverPort:9080

requestURI:/dangwebx-tst/tms/bms/billingQaReportController/datagrid.do

requestURL:http://localhost:9080/dangwebx-tst/tms/bms/billingQaReportController/datagrid.do

servletPath:/tms/bms/billingQaReportController/datagrid.do

queryString:field=id,code,applyDate,filename,reportType,applyUser,outPath

 */
public class MyServletRequestListener implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent arg0) {
        System.out.println("MyServletRequestListener Destory");

    }

    @Override
    public void requestInitialized(ServletRequestEvent arg0) {
        System.out.println("MyServletRequestListener Init");

        Integer count=null;//请求数量
        Object requestCount=arg0.getServletContext().getAttribute("requestCount");
        if(requestCount==null){
            count=0;
        }else{
            count=Integer.valueOf(requestCount.toString());
        }
        count++;
        System.out.println("当前请求数："+count.toString());
        arg0.getServletContext().setAttribute("requestCount", count);

        //serverName
        String serverName=arg0.getServletRequest().getServerName();
        System.out.println("serverName:"+serverName);

        //serverPort
        int serverPort=arg0.getServletRequest().getServerPort();
        System.out.println("serverPort:"+serverPort);

        HttpServletRequest servletRequest=(HttpServletRequest)arg0.getServletRequest();

        //requestURI
        String requestURI=servletRequest.getRequestURI();
        System.out.println("requestURI:"+requestURI);

        //requestURL
        String requestURL=servletRequest.getRequestURL().toString();
        System.out.println("requestURL:"+requestURL);

        //servletPath
        String servletPath=servletRequest.getServletPath();
        System.out.println("servletPath:"+servletPath);

        //queryString
        String queryString=servletRequest.getQueryString();
        System.out.println("queryString:"+queryString);

    }
}
